import cv2 as cv
import numpy as np

# 读取图片
img1 = cv.imread('pic4.jpg')
img2 = cv.imread('pic5.png')
# 灰度化
gray1 = cv.cvtColor(img1,cv.COLOR_BGR2GRAY)
gray2 = cv.cvtColor(img2,cv.COLOR_BGR2GRAY)
# 创建sift特征匹配器
sift = cv.xfeatures2d.SIFT_create()
# 计算描述子与特征点
kp1, des1 = sift.detectAndCompute(gray1, None)
kp2, des2 = sift.detectAndCompute(gray2, None)
# 创建匹配器
index_params = dict(algorithm=1, trees=5)
search_params = dict(checks=50)
flann = cv.FlannBasedMatcher(index_params, search_params)
# 对描述子进行匹配
matches = flann.knnMatch(des1, des2, k=2)
good = []
for i, (m, n) in enumerate(matches):
    if m.distance < 0.7*n.distance:
        good.append(m)


# 绘制匹配点
ret = cv.drawMatchesKnn(img1,kp1,img2,kp2,[good],None)
cv.imshow('img', ret)
cv.waitKey(0)

